class Solution {
public:
    bool isHappy(int n) {
        int slow = n, fast = dfs(n);
        while (slow != fast) {
            slow = dfs(slow);
            fast = dfs(dfs(fast));
        }
        return fast == 1;
    }

    int dfs(int n) {
        int sum = 0;
        while (n) {
            int left = n % 10;
            n = n / 10;
            sum += pow(left, 2);
        }
        return sum;
    }
};